package newcoder;

import java.util.*;

public class NC93t2 {
    Map<Integer, Integer> map;
    int capacity;
    public NC93t2(int capacity) {
        this.capacity = capacity;
        map = new LinkedHashMap<>(capacity);
    }

    public int get(int key) {
        Integer value = map.get(key);
        if(value != null){ // 如果已经有此key
            if(map.size()>1) {
                map.remove(key); // 删除原先的key
                map.put(key, value); // 添加key到最后
            }
        } else {
            return -1;
        }
        return value;
    }

    public void set(int key, int value) {
        if (map.containsKey(key)){ // 已经有此key
            map.remove(key); // 删除原先的key
        }
        else if(map.size()>=capacity) { // 容量达到了最大
            Integer firstKey = map.keySet().iterator().next();
            //map.keySet()将linkedMap的Key转为Set集合
            //set调用迭代器拿到第一个元素即出缓存的key值
            map.remove(firstKey); // 删除第一个key
        }
        map.put(key, value); // 添加key到最后
    }

    public static void main(String[] args) {
        Map<Integer,Integer> map = new LinkedHashMap<>(4);
        map.put(1,1);
        map.put(2,2);
        map.put(3,3);
        Set<Integer> set = map.keySet();
        Iterator<Integer> it = set.iterator();
        System.out.println(it.next());
        System.out.println(it.next());
        System.out.println(it.next());
        it.remove();
        int[] a = new int[]{1,2,3,4,5};
        int[] b ;
        System.out.println();
        b = Arrays.copyOfRange(a,0,3);
        System.out.println();

    }
}
